// https://leetcode.cn/problems/matrix-cells-in-distance-order/
// Created by ade on 2022/10/26.
//
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class Solution {
public:

    vector <vector<int>> allCellsDistOrder1(int rows, int cols, int rCenter, int cCenter) {
        vector <vector<int>> vi;
        vector <vector<int>> res;
        vector <vector<int>> points;
        vi.resize(rows, vector<int>(cols, 0));
        vi[rCenter][cCenter] = 1;
        res.push_back({rCenter, cCenter});
        points.push_back({rCenter, cCenter});
        vector <vector<int>> directions = {{0,  1},
                                           {0,  -1},
                                           {-1, 0},
                                           {1,  0}};
        int num = rows * cols - 1;
        while (num > 0) {
            vector <vector<int>> tmp;
            for (auto &p:points) {
                for (auto &d : directions) {
                    int x = p[0] + d[0];
                    int y = p[1] + d[1];
                    if (x < 0 || x >= rows || y < 0 || y >= cols || vi[x][y] == 1) continue;
                    vi[x][y] = 1;
                    tmp.push_back({x, y});
                    res.push_back({x, y});
                    num--;
                }
            }
            points = tmp;
        }
        return res;
    }

    vector <vector<int>> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
        vector <vector<int>> m;
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                m.push_back({i, j});
            }
        }
        sort(m.begin(), m.end(), [=](vector<int> &a, vector<int> &b) {
            return abs(a[0] - rCenter) + abs(a[1] - cCenter) <= abs(b[0] - rCenter) + abs(b[1] - cCenter);
        });
        return m;
    }

};

int main() {
    Solution so;
    vector <vector<int>> res = so.allCellsDistOrder(3, 4, 0, 1);
    cout << res.size() << endl;
    for (int i = 0; i < 12; i++) {
        cout << res[i][0] << "," << res[i][1] << endl;
    }
    return 0;
}